<template>
	<view class="container flex-c">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="#ffffff" leftWidth="90rpx" rightWidth="90rpx" color="#333" :fixed="true" :padding="false" :border="navBorder" @clickLeft="$goBack(1)">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit"></image>
			</template>
			<text class="title">意见反馈</text>
		</uni-nav-bar>
		<view class="body">
			<view class="feed-type mb40">
				<view class="title">
					<text class="color-red">*</text> 反馈类型 <text class="color-grey">（单选）</text>
				</view>
				<view class="btn-list flex-r">
					<template v-for="(item,index) in feedTypes">
						<text class="btn" :class="{'active': activeType == index}" @tap="typeChange(index)">{{item}}</text>
					</template>
				</view>
			</view>
			<view class="feed-expert mb40" v-if="activeType == 1">
				<view class="title flex-r ac">
					<text class="color-red">*</text> 选择您要投诉的专家
					<text class="color-grey">（单选）</text>
					<text class="select" @tap="selectExpert">{{ expert ? '重新选择专家' : '请选择专家'}}</text>
					<image src="@/public/images/public/yjt_h.png" mode="aspectFit"></image>
				</view>
				<view class="expert flex-r" v-if="expert">
					<view class="author-image">
						<lazy-image class="inheritwh border-round" :src="expert.expertAvatar+'?imageView2/1/w/100/h/100/q/50'" type="expert" fit="cover"></lazy-image>
					</view>
					<view class="author-info flex-c">
						<view class="info-name">
							<text class="text-regular">{{expert.expertName}}</text>
						</view>
						<view class="info-detail text-hidden text-small color-grey" v-if="expert.remark">
							{{expert.remark}}
						</view>
					</view>
				</view>
			</view>
			<view class="feed-content mb40">
				<view class="title">
					<text class="color-red">*</text> 投诉内容 <text class="color-grey">（单选）</text>
				</view>
				<view class="btn-list flex-r">
					<template v-for="(item,index) in feedContent[activeType].listData">
						<text class="btn" :class="{'active': activeContent == index}" @tap="contentChange(index)">{{item.title}}</text>
					</template>
				</view>
			</view>
			<view class="feed-detail mb40">
				<view class="title">
					<text class="color-red">*</text> 投诉内容详细描述 <text class="color-grey">（500字以内）</text>
				</view>
				<view class="text-input flex-c">
					<uni-easyinput class="textarea" type="textarea" autoHeight @input="input" v-model="detail" maxlength="500" placeholder="请详细描述您的问题或建议" :clearable="false" :inputBorder="false"></uni-easyinput>
					<text class="text-num" :class="{'active': textNum == 500}">{{textNum}}/500</text>
				</view>
			</view>
			<view class="feed-image mb40">
				<view class="title">
					上传图片<text class="color-grey">（最多可上传3张图片）</text>
				</view>
				<view class="upload-image flex-r">
					<view class="choose-image" @tap="chooseImg" v-if="tempFilePaths.length < 3">
						<image class="inheritwh" src="@/public/images/user/djsctp.png" mode="aspectFit"></image>
						<text class="color-grey">点击上传图片</text>
					</view>
					<view class="image-list" v-for="(item, index) in tempFilePaths" :key="index">
						<image class="inheritwh" :src="item.path" mode="aspectFill"></image>
						<image class="icon" src="@/public/images/user/sctp.png" mode="aspectFit" @tap="deleteImg(index)"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="submit-box">
			<button type="default" class="active" @tap="submit">提交</button>
		</view>
	</view>
</template>

<script>
	import * as qiniu from 'qiniu-js'
	export default {
		data() {
			return {
				textNum: 0,
				activeType: 0,
				activeContent: 0,
				feedTypes: ['问题反馈', '投诉专家'],
				feedContent: [
					{
						listData: [
							{title: '功能反馈', value: 1},
							{title: '其他建议', value: 2}
						]
					},
					{
						listData: [
							{title:'色情低俗', value: 2},
							{title:'政治敏感', value: 3},
							{title:'广告', value: 4},
							{title:'违法违纪', value: 5},
							{title:'内容不适', value: 6},
							{title:'其他', value: 1}
						]
					}
				],
				imagesList: [],
				expert: null,
				detail: null,
				domainUrl: null,
				tempFilePaths: [],
				token: null,
				navBorder: false
			}
		},
		computed: {
			user() {
				return this.$store.state.user
			},
			complaintsCause() {
				return this.feedContent[this.activeType].listData[this.activeContent].value
			}
		},
		onLoad() {
			console.log(this.activeType)
			console.log(this.complaintsCause);
		},
		onUnload() {
			uni.$off('selectExpert')
			uni.removeStorageSync('searchExpertKey')
		},
		onPageScroll(e) {
			if(e.scrollTop > 10){
				this.navBorder = true
			}else{
				this.navBorder = false
			}
		},
		methods: {
			//提交
			submit() {
				if(!this.detail){
					uni.showToast({
						title: '请填写您要反馈的问题',
						icon: 'none',
						duration: 2000
					})
					return
				}
				let requset = null
				let apiurl = null
				if(this.activeType === 0){
					apiurl = '/api/feedback/add'
					requset = {
						content: this.detail,
						feedType: this.complaintsCause,
						mobile: this.user.phone,
						picUrlList: this.imagesList
					}
					console.log(requset);
				}else{
					if(!this.expert){
						uni.showToast({
							title: '请选择您要投诉的专家',
							icon: 'none',
							duration: 2000
						})
						return
					}
					apiurl = '/api/complaints/add'
					requset = {
						complaintsDescription: this.detail,
						complaintsCause: this.complaintsCause,
						complaintsType: 1,
						expertId: this.expert.expertId,
						picUrlList: this.imagesList
					}
					console.log(requset);
				}
				this.postAdd(apiurl, requset)
			},
			//发送请求添加反馈
			async postAdd(url, requset){
				if(!url || !requset){
					return
				}
				if(this.tempFilePaths[0]){
					await this.getToken()
					await this.uploadAllImg()
					requset.picUrlList = this.imagesList
				}
				this.$http.post({
					url,
					data: {
						...requset
					},
				}).then(data => {
					console.log(data);
					if(data.success){
						uni.showToast({
							title: '提交成功！',
							icon: 'success'
						})
						this.resetData()
					}else{
						uni.showToast({
							title: data.message,
							icon: 'none'
						})
					}
				}).catch((err) => {
					uni.showToast({
						title: '请求错误，请稍后重试',
						icon: 'none'
					})
					console.log(err);
				})
			},
			//重置数据
			resetData() {
				this.detail = null
				this.expert = null
				this.tempFilePaths = []
				this.imagesList = []
				this.activeType = 0
				this.activeContent = 0
			},
			//选项切换
			typeChange(index){
				this.activeType = index
				this.activeContent = 0
				console.log(this.activeType)
				console.log(this.complaintsCause);
			},
			//选项切换
			contentChange(index){
				this.activeContent = index
				console.log(this.activeType)
				console.log(this.complaintsCause);
			},
			//选择专家
			selectExpert() {
				uni.$once('selectExpert', (data) => {
					console.log(data)
					this.expert = data.expert
				})
				this.$Router.push({name: 'selectexpert'})
			},
			//计算输入字数
			input(e) {
				this.textNum = e.length
			},
			//删除图片
			deleteImg(index){
				this.tempFilePaths.splice(index, 1)
				console.log(this.tempFilePaths)
			},
			//选择图片
			chooseImg() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					extension: ['jpg','png'],
					success: (res) => {
						console.log(res.tempFiles[0]);
						this.tempFilePaths.push(res.tempFiles[0])
						console.log(res.tempFiles[0],this.tempFilePaths,'this.tempFilePaths');
					}
				});
			},
			//批量上传图片
			async uploadAllImg() {
				uni.showLoading({
					title: '图片上传中...'
				})
				let len = this.tempFilePaths.length
				for(let i = 0; i < len ; i++) {
					let res = await this.qiniuUpload(this.tempFilePaths[i])
					console.log(res)
					if(res.key){
						let imgUrl = this.domainUrl + '/' + res.key
						console.log(imgUrl)
						this.imagesList.push(imgUrl)
					}
					if(i == len -1){
						uni.hideLoading()
					}
				}
			},
			//上传图片
			uploadImg(tempImagePath) {
				if(this.token){
					let key = this.generateUUID()
					uni.uploadFile({
						url: 'https://upload-z1.qiniup.com',
						filePath: tempImagePath,
						name: 'file',
						formData: {
							key,
							token: this.token
						},
						success: (res) => {
							console.log(res)
							if(res.statusCode == 200 && res.data){
								let path = JSON.parse(res.data).key
								let imgUrl = this.domainUrl + '/' + path
								console.log(imgUrl)
								this.imagesList.push(imgUrl)
							}else{
								uni.showToast({
									title: res.errMsg,
									icon: 'none'
								})
							}
						},
						fail: (err) => {
							console.log('fail', err);
						}
					});
				}
			},
			//七牛上传图片
			qiniuUpload(file) {
				let that = this
				return new Promise((resolve,reject)=>{
					let type = file.type.substr(6)
					console.log(type,'type')
					let key = Date.now() + 'H5.' + type
					const observer = {
						next(res){
							console.log(res);
						},
						error(err){
							console.log(err);
							that.getToken()
							reject(err)
						},
						complete(res){
							console.log(res);
							resolve(res)
						}
					}
					const options = {
						quality: 0.4,
						noCompressIfLarger: true
					}
					//压缩图片
					qiniu.compressImage(file, options).then(data => {
						console.log(file,'file---')
						const observable = qiniu.upload(data.dist, key, this.token)
						const subscription = observable.subscribe(observer) // 上传开始
					})
				})
			},
			async getToken(){
				let result = await this.$CHS.getQiniuToken()
				if(result.token){
					this.token = result.token
					this.domainUrl = result.url
				}
			},
			//唯一标识符UUID
			generateUUID() {
				var d = new Date().getTime();
				if (window.performance && typeof window.performance.now === "function") {
					d += performance.now(); //use high-precision timer if available
				}
				var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
					var r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
				});
				return uuid;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.body{
		margin: 20rpx 0 40rpx;
		padding: 0 20rpx;
		background: #FFFFFF;
		.title{
			font-size: 30rpx;
			line-height: 30rpx;
			font-weight: 500;
			.color-grey{
				font-size: 26rpx;
				line-height: 26rpx;
				font-weight: normal;
				flex: 2;
			}
			.select{
				color: #999999;
				font-size: 28rpx;
				line-height: 28rpx;
			}
			&.flex-r{
				align-items: center;
				image{
					width: 24rpx;
					height: 26rpx;
				}
			}
			.color-red{
				margin-right: 15rpx;
			}
		}
		.btn-list{
			flex-wrap: wrap;
			.btn{
				height: 70rpx;
				background: #F2F5FA;
				border-radius: 10rpx;
				font-size: 26rpx;
				line-height: 66rpx;
				color: #999999;
				margin: 23rpx 20rpx 0 0;
				padding: 0 30rpx;
				border: none;
				&.active{
					background: #0055FF;
					color: #FFFFFF;
				}
			}
		}
		.mb40{
			margin-bottom: 40rpx;
		}
		.feed-type{
			margin-top: 40rpx;
		}
		.feed-expert{
			.expert{
				margin-top: 23rpx;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx;
				background: #F2F5FA;
				border-radius: 10rpx;
				.author-image{
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					background-color: #FFFFFF;
					background-size: 100%;
				}
				.author-info{
					margin-left: 20rpx;
					flex: 2;
					.info-name{
						font-weight: 500;
					}
					.info-detail{
						margin-top: 16rpx;
						max-width: 570rpx;
					}
				}
			}
		}
		.text-input{
			margin: 23rpx 0 40rpx;
			background: #F2F5FA;
			border-radius: 10rpx;
			padding: 20rpx;
			/deep/ .textarea{
				.uni-easyinput__content-textarea{
					padding-top: 0;
				}
				.uni-textarea-placeholder{
					font-size: 26rpx;
				}
			}
			.text-num{
				align-self: flex-end;
				font-size: 26rpx;
				color: #A6A6A6;
				&.active{
					color: $uni-primary;
				}
			}
		}
		.feed-image{
			.upload-image{
				margin-top: 23rpx;
				.choose-image{
					margin-right: 22rpx;
					position: relative;
					width: 222rpx;
					height: 222rpx;
					border-radius: 10rpx;
					image{
						border-radius: 10rpx;
					}
					text{
						position: absolute;
						top: 130rpx;
						left: 32rpx;
						color: #B3B3B3;
					}
				}
				.image-list{
					margin-right: 22rpx;
					position: relative;
					width: 222rpx;
					height: 222rpx;
					border-radius: 10rpx;
					image{
						border-radius: 10rpx;
					}
					.icon{
						position: absolute;
						top: 0;
						right: 0;
						width: 48rpx;
						height: 48rpx;
						border-radius: 0;
					}
				}
				.image-list:last-child{
					margin-right: 0;
				}
			}
		}
	}
	.submit-box{
		padding: 0 20rpx;
		margin: 0 0 calc(var(--safe-area-inset-bottom) + 40rpx);
	}
</style>
